package alone.redis.queue.redisqueue.bean;

import alone.redis.queue.redisqueue.service.SendEmailService;
import alone.redis.queue.redisqueue.service.SendPhoneMessageService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

@Configuration
public class RedisBeanConfig {

    @Bean
    public StringRedisTemplate stringRedisTemplate(JedisConnectionFactory redisConnectionFactory) {

        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
        stringRedisTemplate.setConnectionFactory(redisConnectionFactory);

        return stringRedisTemplate;
    }

    /**
     * redis消息监听器容器
     * 可以添加多个监听不同话题的redis监听器，只需要把消息监听器和相应的消息订阅处理器绑定，该消息监听器
     * 通过反射技术调用消息订阅处理器的相关方法进行一些业务处理
     *
     * @param connectionFactory connectionFactory
     * @return RedisMessageListenerContainer
     */
//MessageListenerAdapter 表示监听频道的不同订阅者
    @Bean
    RedisMessageListenerContainer container2(RedisConnectionFactory connectionFactory,  MessageListenerAdapter messageListenerAdapter,MessageListenerAdapter messageListenerAdapter1) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        //订阅频道
        container.addMessageListener(messageListenerAdapter, new PatternTopic("signIn:user"));
        container.addMessageListener(messageListenerAdapter1, new PatternTopic("signIn:user"));
        return container;
    }

    //表示监听一个频道
    @Bean
    MessageListenerAdapter messageListenerAdapter(SendEmailService sendEmailService) {
        //这个地方 是给messageListenerAdapter 传入一个消息接受的处理器，利用反射的方法调用“MessageReceiveTwo ”
        return new MessageListenerAdapter(sendEmailService, "getMessage");
    }
    @Bean
    MessageListenerAdapter messageListenerAdapter1(SendPhoneMessageService sendPhoneMessageService) {
        //这个地方 是给messageListenerAdapter 传入一个消息接受的处理器，利用反射的方法调用“MessageReceiveTwo ”
        return new MessageListenerAdapter(sendPhoneMessageService, "getMessage");
    }

}